package utils

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"regexp"
)

const (
	ValidatorKey  = "ValidatorKey"
	TranslatorKey = "TranslatorKey"
	locale        = "zh"
)

func TransInit(c *gin.Context) {
	//设置支持语言
	chinese := zh.New()
	english := en.New()
	//设置国际化翻译器
	uni := ut.New(chinese, chinese, english)
	//设置验证器
	val := validator.New()
	//根据参数取翻译器实例
	trans, _ := uni.GetTranslator(locale)

	//注册自定义校验器
	//自定义验证方法
	val.RegisterValidation("password", func(fl validator.FieldLevel) bool {

		regex := []string{
			"[0-9]{1}",
			"[a-z]{1}",
			"[A-Z]{1}",
			"[!@#~$%^&*()+|_]{0,}",
		}

		for _, r := range regex {
			matched, _ := regexp.Match(r, []byte(fl.Field().String()))
			if !matched {
				return matched
			}
		}
		return len(fl.Field().String()) >= 8 && len(fl.Field().String()) <= 20
	})

	//翻译器注册到validator
	switch locale {
	case "zh":
		zhTranslations.RegisterDefaultTranslations(val, trans)
		val.RegisterTagNameFunc(func(fld reflect.StructField) string {
			return fld.Tag.Get("json")
		})

		//自定义翻译器
		val.RegisterTranslation("password", trans, func(ut ut.Translator) error {
			return ut.Add("password", "{0}需包含大写字母、小写字母、数字，长度8～20个字符", true)
		},
			func(ut ut.Translator, fe validator.FieldError) string {
				t, _ := ut.T("password", fe.Field())
				return t
			})

	case "en":
		enTranslations.RegisterDefaultTranslations(val, trans)
		//使用fld.Tag.Get("en_comment")注册一个获取tag的自定义方法
		val.RegisterTagNameFunc(func(fld reflect.StructField) string {
			return fld.Tag.Get("json")
		})

	}

	c.Set(TranslatorKey, trans)
	c.Set(ValidatorKey, val)
}
